// Magnify类,用于实现图片的局部放大
class Magnify {
  // 实例属性
  small = null
  mark = null
  bigImg = null

  // 构造函数
  constructor(small, mark, bigImg) {
    this.small = document.querySelector(small)
    this.mark = document.querySelector(mark)
    this.bigImg = document.querySelector(bigImg)
    this.bindMouseOver()
  }

  // 对small元素绑定鼠标的移入事件
  bindMouseOver() {
    let _this = this
    // 此作用域中的this是Magnify类的实例对象
    this.small.onmouseover = function (e) {
      // 鼠标距浏览器距离	e.clientX
      // 小图片距浏览器距离 small.offsetLeft
      // mark一半的宽度 (mark.offsetWidth)/2
      // 此处是this是small

      // 获得鼠标相对浏览器边缘坐标位置
      let client_x = e.clientX
      let client_y = e.clientY

      // 获得small元素的left和top值
      let small_left = this.offsetLeft
      let small_top = this.offsetTop

      // 获得mark元素的高和宽的一半
      let half_w = _this.mark.offsetWidth / 2
      let half_h = _this.mark.offsetHeight / 2

      // 控制mark元素的top、left的最大和最小值
      let left = client_x - small_left - half_w
      let top = client_y - small_top - half_h
      if (left <= 0) {
        left = 0
      }
      let max_w = this.offsetWidth - _this.mark.offsetWidth
      if (left > max_w) {
        left = max_w
      }
      if (top <= 0) {
        top = 0
      }
      let max_h = this.offsetHeight - _this.mark.offsetHeight
      if (top > max_h) {
        top = max_h
      }
      // 设置mark元素的 top 和 left
      _this.mark.style.top = top + 'px'
      _this.mark.style.left = left + 'px'

      // 计算大图和小图宽高比例
      let rate_w = _this.bigImg.offsetWidth / this.offsetWidth
      let rate_h = _this.bigImg.offsetHeight / this.offsetHeight

      // 设置大图的top和left的值
      _this.bigImg.style.top = -top * rate_h + 'px'
      _this.bigImg.style.left = -left * rate_w + 'px'
    }
  }
}
